package com.smartleanx.module.hrm.service.employee;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.smartleanx.framework.common.enums.BizTypeEnum;
import com.smartleanx.framework.common.pojo.PageResult;
import com.smartleanx.framework.common.util.collection.CollectionUtils;
import com.smartleanx.framework.common.util.collection.MapUtils;
import com.smartleanx.module.hrm.app.empRisk.EmployeeRiskHandleService;
import com.smartleanx.module.hrm.controller.admin.employee.contract.*;
import com.smartleanx.module.hrm.controller.admin.employee.vo.EmployeeDashboardPageReqVO;
import com.smartleanx.module.hrm.convert.employee.contract.EmployeeContractConvert;
import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeDO;
import com.smartleanx.module.hrm.eums.employee.BizFileTypeEnum;
import com.smartleanx.module.hrm.eums.employee.EmployeeContractStatusEnum;
import com.smartleanx.module.hrm.eums.employee.EmployeeContractTypeEnum;
import com.smartleanx.module.hrm.eums.employee.EmploymentFormEnum;
import com.smartleanx.module.hrm.eums.risk.RiskTypeEnum;
import com.smartleanx.module.hrm.intergration.FileServiceProvider;
import com.smartleanx.module.infra.api.file.dto.FileRefQueryDTO;
import com.smartleanx.module.infra.api.file.dto.FileRefRespDTO;
import com.smartleanx.module.infra.api.file.dto.FileRefSaveBaseDTO;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import com.smartleanx.module.hrm.dal.dataobject.employee.EmployeeContractDO;
import com.smartleanx.framework.common.util.object.BeanUtils;

import com.smartleanx.module.hrm.dal.mysql.employee.EmployeeContractMapper;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.smartleanx.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.smartleanx.module.hrm.enums.ErrorCodeConstants.*;

/**
 * 员工合同 Service 实现类
 *
 * @author tengcj
 */
@Service
@Validated
public class EmployeeContractServiceImpl implements EmployeeContractService {

    @Resource
    private EmployeeContractMapper employeeContractMapper;

    @Resource
    private EmployeeService employeeService;

    @Resource
    private FileServiceProvider fileServiceProvider;

    @Resource
    @Lazy
    private EmployeeRiskHandleService employeeRiskHandleService;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public Long createEmployeeContract(EmployeeContractSaveReqVO createReqVO) {
        // 数据校验
        if (Objects.nonNull(createReqVO.getEndTime())) {
            if (createReqVO.getStartTime().compareTo(createReqVO.getEndTime()) > 0) {
                throw exception(CONTRACT_START_TIME_UNLATER_END_TIME);
            }
        }
        validateContractInProgress(createReqVO);
        // 插入
        EmployeeContractDO employeeContract = BeanUtils.toBean(createReqVO, EmployeeContractDO.class);
        employeeContractMapper.insert(employeeContract);

        List<FileRefSaveBaseDTO> fileRefList = new ArrayList<>();
        // 添加附件关联关系
        createFileRefList(createReqVO.getContractFileIdList(), BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode(), fileRefList);
        createFileRefList(createReqVO.getOtherFileIdList(), BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode(), fileRefList);
        fileServiceProvider.createFileRefByBizTypeAndRecordId(fileRefList, BizTypeEnum.EMPLOYEE_LABOR_CONTRACT.getValue(), employeeContract.getId());
        employeeRiskHandleService.execute(Collections.singleton(createReqVO.getEmployeeId()), RiskTypeEnum.SOCIAL_SECURITY_PAYMENT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(createReqVO.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(createReqVO.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT_EXPIRATION.getCode());
        employeeRiskHandleService.execute(Collections.singleton(createReqVO.getEmployeeId()), RiskTypeEnum.PROBATION_PERIOD.getCode());

        // 返回
        return employeeContract.getId();
    }

    @Override
    public void updateEmployeeContract(EmployeeContractSaveReqVO updateReqVO) {
        Long employeeId = updateReqVO.getEmployeeId();

        EmployeeDO employee = employeeService.getEmployeeById(employeeId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS);
        }
        // 数据校验
        if (Objects.nonNull(updateReqVO.getEndTime())) {
            if (updateReqVO.getStartTime().compareTo(updateReqVO.getEndTime()) > 0) {
                throw exception(CONTRACT_START_TIME_UNLATER_END_TIME);
            }
        }
        validateContractInProgress(updateReqVO);

        // 校验存在
        validateEmployeeContractExists(updateReqVO.getId());
        // 更新
        EmployeeContractDO updateObj = BeanUtils.toBean(updateReqVO, EmployeeContractDO.class);
        employeeContractMapper.updateContract(updateObj);

        // 文件关联关系
        List<FileRefSaveBaseDTO> fileRefList = new ArrayList<>();
        // 添加附件关联关系
        createFileRefList(updateReqVO.getContractFileIdList(), BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode(), fileRefList);
        // 其他文件类型再分类，避免影响到调动、转正的其他文件类型
        createFileRefList(updateReqVO.getOtherFileIdList(), BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode(), fileRefList);
        fileServiceProvider.crudFileRefByBizTypeAndRecordId(fileRefList, BizTypeEnum.EMPLOYEE_LABOR_CONTRACT.getValue(), updateObj.getId());
        employeeRiskHandleService.execute(Collections.singleton(updateObj.getEmployeeId()), RiskTypeEnum.SOCIAL_SECURITY_PAYMENT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(updateObj.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(updateObj.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT_EXPIRATION.getCode());
        employeeRiskHandleService.execute(Collections.singleton(updateObj.getEmployeeId()), RiskTypeEnum.PROBATION_PERIOD.getCode());

    }

    private void createFileRefList(List<Long> fileIdList, Integer bizFileType, List<FileRefSaveBaseDTO> fileRefList) {
        if (CollUtil.isEmpty(fileIdList)) {
            return;
        }
        for (Long fileId : fileIdList) {
            FileRefSaveBaseDTO dto = new FileRefSaveBaseDTO();
            dto.setFileId(fileId);
            dto.setBizFileType(bizFileType);
            fileRefList.add(dto);
        }
    }

    @Override
    public void deleteEmployeeContract(Long id) {

        EmployeeContractDO contractDO = employeeContractMapper.selectById(id);

        // 删除
        if (employeeContractMapper.deleteById(id) < 1) {
            throw exception(EMPLOYEE_CONTRACT_NOT_EXISTS);
        }
        // 文件关联关系
        List<FileRefSaveBaseDTO> fileRefList = new ArrayList<>();
        // 添加附件关联关系
        createFileRefList(Collections.emptyList(), BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode(), fileRefList);
        // 其他文件类型再分类，避免影响到调动、转正的其他文件类型
        createFileRefList(Collections.emptyList(), BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode(), fileRefList);
        fileServiceProvider.crudFileRefByBizTypeAndRecordId(fileRefList, BizTypeEnum.EMPLOYEE_LABOR_CONTRACT.getValue(), id);
        employeeRiskHandleService.execute(Collections.singleton(contractDO.getEmployeeId()), RiskTypeEnum.SOCIAL_SECURITY_PAYMENT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(contractDO.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT.getCode());
        employeeRiskHandleService.execute(Collections.singleton(contractDO.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT_EXPIRATION.getCode());
        employeeRiskHandleService.execute(Collections.singleton(contractDO.getEmployeeId()), RiskTypeEnum.PROBATION_PERIOD.getCode());

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByEmployeeId(Long employeeId) {
        if (employeeId == null) {
            return;
        }
        List<EmployeeContractDO> contractDOS = employeeContractMapper.selectListByEmployeeId(employeeId);
        if (CollUtil.isNotEmpty(contractDOS)) {
            // 文件关联关系
            List<FileRefSaveBaseDTO> fileRefList = new ArrayList<>();
            // 添加附件关联关系
            createFileRefList(Collections.emptyList(), BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode(), fileRefList);
            // 其他文件类型再分类，避免影响到调动、转正的其他文件类型
            createFileRefList(Collections.emptyList(), BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode(), fileRefList);
            contractDOS.forEach(i -> {
                // 扫描预警
                employeeRiskHandleService.execute(Collections.singleton(i.getEmployeeId()), RiskTypeEnum.SOCIAL_SECURITY_PAYMENT.getCode());
                employeeRiskHandleService.execute(Collections.singleton(i.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT.getCode());
                employeeRiskHandleService.execute(Collections.singleton(i.getEmployeeId()), RiskTypeEnum.LABOR_CONTRACT_EXPIRATION.getCode());
                employeeRiskHandleService.execute(Collections.singleton(i.getEmployeeId()), RiskTypeEnum.PROBATION_PERIOD.getCode());
                fileServiceProvider.crudFileRefByBizTypeAndRecordId(fileRefList, BizTypeEnum.EMPLOYEE_LABOR_CONTRACT.getValue(), i.getId());
            });
        }
        // 删除员工合同信息
        deleteEmployeeContract(employeeId);
        // 删除
        employeeContractMapper.deleteByEmployeeId(employeeId);

    }

    private void validateEmployeeContractExists(Long id) {
        if (employeeContractMapper.selectById(id) == null) {
            throw exception(EMPLOYEE_CONTRACT_NOT_EXISTS);
        }
    }

    /**
     * @param createReqVO
     */
    private void validateContractInProgress(EmployeeContractSaveReqVO createReqVO) {
        Long employeeId = createReqVO.getEmployeeId();

        EmployeeDO employee = employeeService.getEmployeeById(employeeId);
        if (employee == null) {
            throw exception(EMPLOYEE_NOT_EXISTS);
        }
        // 类型校验
        List<Integer> type = Stream.of(EmployeeContractTypeEnum.FIXED_TERM.gettype(), EmployeeContractTypeEnum.NO_FIXED_TERM.gettype()
                , EmployeeContractTypeEnum.TASK_CONTRACT.gettype()).collect(Collectors.toList());
        if (employee.getEmploymentForm().equals(EmploymentFormEnum.FORMAL.getCode())) {
            if (!type.contains(createReqVO.getContractType())) {
                throw exception(EMPLOYEE_FORMAL_CONTRACTS);
            }
        }
        if (employee.getEmploymentForm().equals(EmploymentFormEnum.INFORMAL.getCode())) {
            if (type.contains(createReqVO.getContractType())) {
                throw exception(EMPLOYEE_INFORMAL_CONTRACTS);
            }
        }
        List<EmployeeContractDO> contractDOS = employeeContractMapper.selectListByEmployeeIds(Collections.singleton(createReqVO.getEmployeeId()));
        // 去除自己
        if (Objects.nonNull(createReqVO.getId())) {
            contractDOS.removeIf(c -> c.getId().equals(createReqVO.getId()));
        }
        if (CollUtil.isNotEmpty(contractDOS)) {
            // 合同期限不允许超过6个月
            List<Integer> monthType = Stream.of(EmployeeContractTypeEnum.INTERNSHIP_AGREEMENT.gettype(),
                    EmployeeContractTypeEnum.LABOR_CONTRACT.gettype(), EmployeeContractTypeEnum.REEMPLOYMENT_AGREEMENT.gettype()).collect(Collectors.toList());
            if (monthType.contains(createReqVO.getContractType())) {
                if (ChronoUnit.MONTHS.between(createReqVO.getStartTime(), createReqVO.getEndTime()) > 6) {
                    throw exception(EMPLOYEE_LABOR_CONTRACT_OVERDUE);
                }

            }

            // 无固定期限合同类型
            List<Integer> collect = Stream.of(EmployeeContractTypeEnum.NO_FIXED_TERM.gettype(), EmployeeContractTypeEnum.TASK_CONTRACT.gettype()).collect(Collectors.toList());

            // 除劳务合同外，其他合同均直允许有一个执行中，且日期不可穿插
            if (!createReqVO.getContractType().equals(EmployeeContractTypeEnum.LABOR_CONTRACT.gettype())) {
                for (EmployeeContractDO contractDO : contractDOS) {
                    if(contractDO.getTerminationStatus()){
                        continue;
                    }
                    if (collect.contains(contractDO.getContractType())) {
                        if (collect.contains(createReqVO.getContractType())) {
                            throw exception(EMPLOYEE_ONE_NO_FIXED_TERM_CONTRACT);
                        }
                        if (!contractDO.getStartTime().isBefore(createReqVO.getStartTime()) && !createReqVO.getEndTime().isBefore(contractDO.getStartTime())) {
                            throw exception(EMPLOYEE_CONTRACT_IN_PROGRESS);
                        }
                    } else {
                        LocalDateTime startTime = createReqVO.getStartTime();
                        //上一份合同结束时间
                        LocalDateTime oldEndTime = contractDO.getEndTime();
                        if(null != contractDO.getTerminationTime()){
                            oldEndTime = contractDO.getTerminationTime();
                        }
                        if (!contractDO.getStartTime().isAfter(startTime) && !startTime.isAfter(oldEndTime)) {
                            throw exception(EMPLOYEE_CONTRACT_IN_PROGRESS);
                        }
                    }
                }
            }
            // 判断续签合同日期是否合规
//            List<EmployeeContractDO> list = contractDOS.stream().sorted(Comparator.comparing(EmployeeContractDO::getId).reversed()).collect(Collectors.toList());
//            LocalDateTime endTime = list.get(0).getEndTime();
//            if (Objects.nonNull(endTime) && createReqVO.getStartTime().compareTo(endTime.plusDays(1)) != 0) {
//                throw exception(EMPLOYEE_RENEWAL_CONTRACT);
//            }
            List<EmployeeContractDO> list = contractDOS.stream().sorted(Comparator.comparing(EmployeeContractDO::getId).reversed()).collect(Collectors.toList());
            EmployeeContractDO employeeContractDO = list.get(0);
            LocalDateTime endTime = employeeContractDO.getEndTime();
            if(employeeContractDO.getTerminationStatus() || employeeContractDO.getTerminationTime() != null){
                endTime = employeeContractDO.getTerminationTime();
            }

            if (Objects.nonNull(endTime) && createReqVO.getStartTime().compareTo(endTime.plusDays(1)) < 0) {
                throw exception(EMPLOYEE_RENEWAL_CONTRACT1);
            }

        }
    }

    @Override
    public List<EmployeeContractDO> getEmployeeContractList(Collection<Long> employeeIdList) {
        return employeeContractMapper.selectListByEmployeeIds(employeeIdList);
    }


    @Override
    public List<EmployeeContractDO> getInProgressContractList(Collection<Long> employeeIds) {

        List<EmployeeContractDO> list = employeeContractMapper.selectListByEmployeeIds(employeeIds);
        // 剔除已终止的合同
        list.removeIf(EmployeeContractDO::getTerminationStatus);
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 获取执行中合同
        LocalDate now = LocalDate.now();
        List<EmployeeContractDO> removeList = new ArrayList<>();
        for (EmployeeContractDO con : list) {
            // 如果有终止日期
            if (Objects.nonNull(con.getTerminationTime()) && con.getTerminationTime().toLocalDate().isAfter(now)) {
                removeList.add(con);
                continue;
            }
            // 无固定期限合同
            if (con.getContractType().equals(EmployeeContractTypeEnum.NO_FIXED_TERM.gettype()) ||
                    con.getContractType().equals(EmployeeContractTypeEnum.TASK_CONTRACT.gettype())) {
                if (con.getStartTime().toLocalDate().isAfter(now)) {
                    removeList.add(con);
                }
            } else {
                if (con.getEndTime().toLocalDate().isBefore(now) || con.getStartTime().toLocalDate().isAfter(now)) {
                    removeList.add(con);
                }
            }
        }
        if (CollUtil.isNotEmpty(removeList)) {
            list.removeAll(removeList);
        }
        return list;
    }

    @Override
    public Integer contractStatus(EmployeeContractRepVo repVo) {
        LocalDate now = LocalDate.now();
        if (Objects.nonNull(repVo.getStartTime())) {
            if (now.isBefore(repVo.getStartTime().toLocalDate())) {
                return EmployeeContractStatusEnum.UN_EXECUTED.getCode();
            }
            if (now.compareTo(repVo.getStartTime().toLocalDate()) == 0) {
                return EmployeeContractStatusEnum.IN_PROGRESS.getCode();
            }
            if (now.isAfter(repVo.getStartTime().toLocalDate()) && Objects.isNull(repVo.getEndTime())) {
                return EmployeeContractStatusEnum.IN_PROGRESS.getCode();
            }
            if (Objects.nonNull(repVo.getEndTime())) {
                if (now.isAfter(repVo.getStartTime().toLocalDate()) && now.isBefore(repVo.getEndTime().toLocalDate())) {
                    return EmployeeContractStatusEnum.IN_PROGRESS.getCode();
                }
                if (now.isAfter(repVo.getEndTime().toLocalDate())) {
                    return EmployeeContractStatusEnum.EXPIRED.getCode();
                }
            }
        }

        return null;
    }

    @Override
    public EmployeeContractSimpleRespVo getContractSimple(Integer year, Long startTime) {
        if (Objects.nonNull(startTime)) {
            LocalDateTime start = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
            EmployeeContractRepVo repVo = EmployeeContractRepVo.builder().startTime(start).year(year).build();
            if (Objects.nonNull(year)) {
                LocalDateTime endTime = repVo.getStartTime().plusYears(repVo.getYear()).minusDays(1);
                repVo.setEndTime(endTime);
                return EmployeeContractSimpleRespVo.builder().status(contractStatus(repVo)).endTime(endTime).build();
            }
            return EmployeeContractSimpleRespVo.builder().status(contractStatus(repVo)).build();

        }
        return null;
    }

    @Override
    public EmployeeContractRespVO getEmployeeContract(Long id) {
        EmployeeContractDO contractDO = employeeContractMapper.selectById(id);
        EmployeeContractRepVo repVo = EmployeeContractRepVo.builder().startTime(contractDO.getStartTime())
                .endTime(contractDO.getEndTime()).contractType(contractDO.getContractType()).build();
        EmployeeContractRespVO result = BeanUtils.toBean(contractDO, EmployeeContractRespVO.class);

        List<FileRefRespDTO> fileList = getFileList(Collections.singletonList(contractDO.getId()));
        if (CollUtil.isNotEmpty(fileList)) {
            Map<Integer, List<FileRefRespDTO>> listMap = CollectionUtils.convertMultiMap(fileList, FileRefRespDTO::getBizFileType);
            result.setContractFileIdList(listMap.get(BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode()));
            result.setOtherFileIdList(listMap.get(BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode()));
        }
        result.setStatus(contractStatus(repVo));
        if (contractDO.getTerminationStatus()) {
            result.setStatus(EmployeeContractStatusEnum.TERMINATION.getCode());
        }
        return result;
    }

    public List<FileRefRespDTO> getFileList(List<Long> ids) {
        FileRefQueryDTO queryDTO = new FileRefQueryDTO();
        queryDTO.setBizRecordIds(ids);
        queryDTO.setBizType(BizTypeEnum.EMPLOYEE_LABOR_CONTRACT.getValue());
        return fileServiceProvider.getFileRef(queryDTO);
    }


    @Override
    public List<EmployeeContractRespVO> getEmployeeContractList(Long employeeId) {
        List<EmployeeContractRespVO> respVOList = BeanUtils.toBean(employeeContractMapper.selectListByEmployeeId(employeeId),EmployeeContractRespVO.class);
        if (CollUtil.isEmpty(respVOList)) {
            return respVOList;
        }
        // 回显合同状态
        for (EmployeeContractRespVO vo : respVOList) {
            vo.setStatus(contractStatus(EmployeeContractRepVo.builder().startTime(vo.getStartTime()).endTime(vo.getEndTime()).build()));
            if (vo.getTerminationStatus()) {
                vo.setStatus(EmployeeContractStatusEnum.TERMINATION.getCode());
            }
        }

        // 获取文件
        List<Long> ids = respVOList.stream().map(EmployeeContractRespVO::getId).collect(Collectors.toList());
        List<FileRefRespDTO> fileRef = getFileList(ids);
        Map<Long, List<FileRefRespDTO>> recordMap = CollectionUtils.convertMultiMap(fileRef, FileRefRespDTO::getBizRecordId);

        for (EmployeeContractRespVO respVO : respVOList) {
            List<FileRefRespDTO> refRespDTOS = recordMap.get(respVO.getId());
            Map<Integer, List<FileRefRespDTO>> listMap = CollectionUtils.convertMultiMap(refRespDTOS, FileRefRespDTO::getBizFileType);
            respVO.setContractFileIdList(CollUtil.newArrayList(listMap.get(BizFileTypeEnum.CONTRACT_IN_SERVICE.getCode())));
            respVO.setOtherFileIdList(CollUtil.newArrayList(listMap.get(BizFileTypeEnum.OTHER_IN_SERVICE_CONTRACT.getCode())));
        }

        return respVOList;
    }

    @Override
    public Map<Long, List<EmployeeContractRespVO>> getEmployeeContractMap(Collection<Long> employeeIds) {
        List<EmployeeContractDO> list = getInProgressContractList(employeeIds);
        if (CollUtil.isEmpty(list)) {
            return new HashMap<>();
        }
        return CollectionUtils.convertMultiMap(BeanUtils.toBean(list, EmployeeContractRespVO.class), EmployeeContractRespVO::getEmployeeId);
    }

    @Override
    public List<EmployeeContractRespVO> selectEmployeeAllContract() {
        return BeanUtils.toBean(employeeContractMapper.selectList(), EmployeeContractRespVO.class);
    }

    @Override
    public PageResult<EmployeeContractDO> selectContractExpirationPage(EmployeeDashboardPageReqVO pageReqVO) {
        return employeeContractMapper.selectContractExpirationPage(pageReqVO);
    }

    @Override
    public void updateContractBatch(List<EmployeeContractDO> list) {
        employeeContractMapper.updateBatch(list);
    }

    @Override
    public void terminationContract(ContractTerminationSaveRepVO saveRepVO) {

        EmployeeContractDO contractDO = employeeContractMapper.selectById(saveRepVO.getId());
        // 校验存在
        if (contractDO == null) {
            throw exception(EMPLOYEE_CONTRACT_NOT_EXISTS);
        }
        validateEmployeeContractExists(saveRepVO.getId());
        //校验终止日期 ： 不能早于合同开始日期，不能晚于合同结束日期
        if (saveRepVO.getTerminationTime().isBefore(contractDO.getStartTime())) {
            throw exception(CONTRACT_TERMINATION_TIME_BEFORE_START_TIME);
        }
        if (!contractDO.getContractType().equals(EmployeeContractTypeEnum.TASK_CONTRACT.gettype()) &&
                !contractDO.getContractType().equals(EmployeeContractTypeEnum.NO_FIXED_TERM.gettype())) {
            if (saveRepVO.getTerminationTime().isAfter(contractDO.getEndTime())) {
                throw exception(CONTRACT_TERMINATION_TIME_AFTER_END_TIME);
            }
        }

        EmployeeContractDO updateDo = new EmployeeContractDO();
        updateDo.setId(saveRepVO.getId());
        updateDo.setTerminationTime(saveRepVO.getTerminationTime());
        updateDo.setTerminationReason(saveRepVO.getTerminationReason());
        updateDo.setTerminationStatus(Boolean.FALSE);
        if (saveRepVO.getTerminationTime().toLocalDate().isBefore(LocalDate.now())) {
            updateDo.setTerminationStatus(Boolean.TRUE);
        }
        employeeContractMapper.updateById(updateDo);
    }

    @Override
    public EmployeeContractDO getLastContract(Long employeeId) {
        List<EmployeeContractDO> list = employeeContractMapper.selectListByEmployeeId(employeeId);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        // List<EmployeeContractDO> collect = list.stream().sorted(Comparator.comparing(EmployeeContractDO::getStartTime).reversed()).collect(Collectors.toList());
        list.sort(Comparator.comparing(EmployeeContractDO::getStartTime).reversed());
        return list.get(0);
    }

    @Override
    public void deleteByEmployeeIdNew(Long employeeId) {
        if (employeeId != null) {
            employeeContractMapper.deleteByEmployeeId(employeeId);
        }
    }
}
